package org.example.os.synchronous.producer_comsumer;

import java.util.concurrent.Exchanger;

/**
 * 交换器方式，适用于单生产者和单消费者
 */
public class ExchangerAchievement {
    private final Exchanger<Integer> exchanger = new Exchanger<>();
    private volatile boolean isProducing = true;

    public void produce() throws InterruptedException {
        int value = 0;
        while (isProducing) {
            System.out.println("生产者生产: " + value);
            value = exchanger.exchange(value);
            Thread.sleep(1000);
        }
    }

    public void consume() throws InterruptedException {
        int receivedValue = 0;
        while (true) {
            receivedValue = exchanger.exchange(null);
            System.out.println("消费者消费: " + receivedValue);
            Thread.sleep(1000);
        }
    }

    public void stop() {
        isProducing = false;
    }
}
